#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@文件 ：api_param_check.py
@作者 : mengly
@时间 : 2023/7/12 14:16
@版本 : 1.0
说明  ： 
'''
from sanic import json
from functools import wraps
from loguru import logger


def params_check(need_params: set,check_body='json'):
    """Check the parameters required from the request."""

    def decorator(f):
        @wraps(f)
        async def decorated_function(request, *args, **kwargs):
            # logger.info('params_check')
            if request.method in ["POST", "PUT", "DELETE"]:
                try:
                    if check_body=='json':
                        params = request.json.keys()
                    elif check_body=='form':
                        params=request.form.keys()
                    else:
                        return json(status=400, body={'status': 400, 'message': "参数校验不通过"})
                except Exception as e :
                    logger.exception(e)
                    return json(status=400, body={'status': 400, 'message': "参数校验不通过",'error':str(e)})
            else:
                params = request.args.keys()
            set_diff=set(need_params) - set(params)
            if set_diff:
                logger.warning("参数缺失:%s"%set_diff)
                return json(status=400, body={'status':400,'message':"参数缺失:%s"%set_diff})

            response = await f(request, *args, **kwargs)
            return response

        return decorated_function

    return decorator

# def param_check2(need_params: set):
#     """Check the parameters required from the request."""
#     logger.info('params_check')
#     def decorator(f):
#         @wraps(f)
#         async def decorated_function(instance, request, *args, **kwargs):
#             if request.method in ["POST", "PUT", "DELETE"]:
#                 params = request.json.keys()
#             else:
#                 params = request.args.keys()
#
#             if set(need_params) - set(params):
#                 return json(status=400, body={'status':400,'message':"参数校验缺失"})
#
#             response = await f(instance, request, *args, **kwargs)
#             return response
#
#         return decorated_function
#
#     return decorator